package cn.yiya.shiji.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.yiya.shiji.R;
import cn.yiya.shiji.activity.GoodsDetailActivity;
import cn.yiya.shiji.activity.GoodsListFilterActivity;
import cn.yiya.shiji.activity.LoginActivity;
import cn.yiya.shiji.activity.SingleBrandOrderActivity;
import cn.yiya.shiji.adapter.GoodsListOrderAdapter;
import cn.yiya.shiji.adapter.MallGoodsAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.entity.GoodsIdInfo;
import cn.yiya.shiji.entity.MallLimitOptionInfo;
import cn.yiya.shiji.entity.MallLimitOptionObject;
import cn.yiya.shiji.entity.ParaObject;
import cn.yiya.shiji.entity.ShopGoodsBrandGoodsObject;
import cn.yiya.shiji.entity.SortInfo;
import cn.yiya.shiji.entity.goodes.NewGoodsItem;
import cn.yiya.shiji.utils.SimpleUtils;

/**
 * Created by chenjian on 2015/11/18.
 */
public class BrandsGoodsShowFragment extends BaseFragment implements View.OnClickListener{
    private View mView;

    private Handler mHandler;
    private int brandId;

    /*
    筛选和排序按钮
     */
    private TextView tvOrder;
    private TextView tvFilter;
    /*
    左侧排序popupwindow
     */
    private PopupWindow orderPopupWindow;
    private LinearLayout llytOrder;
    private RecyclerView rycvOrder;
    private GoodsListOrderAdapter goodsListOrderAdapter;
    /*
    商品列表
     */
    private RecyclerView mRecyclerView;
    private MallGoodsAdapter mallGoodsAdapter;
    private ArrayList<NewGoodsItem> mLists = new ArrayList<>();
    /*
    筛选后无商品的提示布局
     */
    private RelativeLayout rlytNollGoods;
    private TextView tvDefaultNull;


    private int nOffset = 0;
    private boolean isBottom;
    private int lastVisibleItemPosition;

    private ParaObject post;
    private MallLimitOptionInfo mInfos;
    private String gendersKey = "";
    private String gendersName = "";
    private String category_ids = "";
    private String price_ranges_id = "";
    private String sort_ids = "";
    private String genders = "";
    private String color = "";
    private String size = "";
    private String brand_ids = "";
    private SingleBrandOrderActivity activity;
    private boolean bReload = true;
    private static final int REQUEST_FILTER = 1001;
    private static final String ALL = "全部";
    private static final int SOURCE_BRAND = 3;
    private static final int REQUEST_LOGIN = 110;
    private boolean isLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler(getActivity().getMainLooper());
        brandId = ((SingleBrandOrderActivity)getActivity()).brand_id;
        activity = (SingleBrandOrderActivity)getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_brands_goods_show, null);
        initLoginState();
        initPostData();
        initViews();
        initEvents();
        init();
        return mView;
    }

    private void initLoginState() {
        new RetrofitRequest<>(ApiRequest.getApiShiji().isLogin()).handRequest(
                new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            isLogin = true;
                        } else if (msg.isLossLogin()) {
                            isLogin = false;
                        }
                    }
                }
        );
    }



    private void initPostData() {
        post = new ParaObject();
        mInfos = new MallLimitOptionInfo();
        ArrayList<SortInfo> genderList = new ArrayList<>();
        ArrayList<SortInfo> brandList = new ArrayList<>();
        ArrayList<SortInfo> categoryList = new ArrayList<>();
        ArrayList<SortInfo> priceList = new ArrayList<>();
        ArrayList<SortInfo> colorList = new ArrayList<>();
        ArrayList<SortInfo> sortList = new ArrayList<>();

        SortInfo gInfo = new SortInfo();
        gInfo.setCheck(true);
        gInfo.setName(ALL);
        gInfo.setKey("");
        genderList.add(gInfo);
        mInfos.setGenders(genderList);

        SortInfo bInfo = new SortInfo();
        bInfo.setName(ALL);
        bInfo.setCheck(true);
        brandList.add(bInfo);
        mInfos.setBrands(brandList);

        SortInfo cInfo = new SortInfo();
        cInfo.setCheck(true);
        cInfo.setName(ALL);
        categoryList.add(cInfo);
        mInfos.setCategories(categoryList);

        SortInfo pInfo = new SortInfo();
        pInfo.setCheck(true);
        pInfo.setName(ALL);
        priceList.add(pInfo);
        mInfos.setPrice_ranges(priceList);

        SortInfo soInfo = new SortInfo();
        soInfo.setCheck(true);
        soInfo.setName("默认排序");
        sortList.add(soInfo);
        mInfos.setSorts(sortList);

        SortInfo coInfo = new SortInfo();
        coInfo.setCheck(true);
        coInfo.setName(ALL);
        colorList.add(coInfo);
        mInfos.setColor(colorList);
    }

    private void getCategoryData() {

        new RetrofitRequest<MallLimitOptionObject>(ApiRequest.getApiShiji().getShopGoodsBrandOption(String.valueOf(brandId))).
                handRequest(new MsgCallBack() {
                    @Override
                    public void onResult(HttpMessage msg) {
                        if (msg.isSuccess()) {
                            MallLimitOptionObject object = (MallLimitOptionObject) msg.obj;
                            //对品类数组进行分类
                            if (object == null || object.getList() == null) {
                                return;
                            }
                            ArrayList<SortInfo> caList = object.getList().getCategories();

                            HashMap<String, ArrayList<SortInfo>> maps = new HashMap<>();

                            for (int i = 0; i < caList.size(); i++) {
                                String productTypeId = caList.get(i).getProduct_type_id() + "";
                                if (maps.get(productTypeId) == null) {
                                    ArrayList<SortInfo> productTypeIds = new ArrayList<>();
                                    productTypeIds.add(caList.get(i));
                                    maps.put(productTypeId, productTypeIds);
                                } else {
                                    ArrayList<SortInfo> productTypeIds = maps.get(productTypeId);
                                    productTypeIds.add(caList.get(i));
                                    maps.put(productTypeId, productTypeIds);
                                }
                            }

                            Iterator iter = maps.entrySet().iterator();
                            while (iter.hasNext()) {
                                Map.Entry entry = (Map.Entry) iter.next();
                                ArrayList<SortInfo> productCategories = (ArrayList<SortInfo>) entry.getValue();
                                mInfos.getCategories().addAll(productCategories);
                            }

                            mInfos.getGenders().addAll(object.getList().getGenders());
                            if (object.getList().getSize() != null) {
                                for (int i = 0; i < object.getList().getSize().size(); i++) {
                                    SortInfo sortInfo = new SortInfo();
                                    sortInfo.setName(ALL);
                                    sortInfo.setCheck(true);
                                    object.getList().getSize().get(i).getSizes().add(0, sortInfo);
                                }
                            }
                            mInfos.setSize(object.getList().getSize());
                            mInfos.getPrice_ranges().addAll(object.getList().getPrice_ranges());
                            mInfos.getColor().addAll(object.getList().getColor());
                            mInfos.getSorts().addAll(object.getList().getSorts());
                            if (getActivity() == null) {
                                return;
                            }
                            if(((SingleBrandOrderActivity)getActivity()).needOrder){
                                initOrderData(((SingleBrandOrderActivity)getActivity()).orderId);
                                ((SingleBrandOrderActivity)getActivity()).needOrder = false;
                            }
                            mInfos.setBrands(object.getList().getBrands());
                        }
                    }
                }
        );

    }

    // 获取分类数据
    private void getOptionPostData(MallLimitOptionInfo data) {
        if(data != null) {
            genders = "";
            category_ids = "";
            sort_ids = "";
            price_ranges_id = "";
            brand_ids = "";
            color = "";

            mInfos = data;

            if (mInfos.getGenders() != null) {
                for (int i = 0; i < mInfos.getGenders().size(); i++) {
                    SortInfo gInfo = mInfos.getGenders().get(i);
                    if (gInfo.isCheck()) {
                        genders = gInfo.getKey();
                    }
                }
            }

            if (mInfos.getCategories() != null) {
                for (int i = 0; i < mInfos.getCategories().size(); i++) {
                    SortInfo cInfo = mInfos.getCategories().get(i);
                    if (cInfo.isCheck()) {
                        category_ids = cInfo.getId() + "";
                        if (mInfos.getSize() != null) {
                            for (int j = 0; j < mInfos.getSize().size(); j++) {
                                if (cInfo.getProduct_type_id() == mInfos.getSize().get(j).getProduct_type_id()) {
                                    ArrayList<SortInfo> sizeList = mInfos.getSize().get(j).getSizes();
                                    for (int n = 0; n < sizeList.size(); n++) {
                                        if (sizeList.get(n).isCheck()) {
                                            size = sizeList.get(n).getId() + "";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (mInfos.getPrice_ranges() != null) {
                for (int i = 0; i < mInfos.getPrice_ranges().size(); i++) {
                    SortInfo pInfo = mInfos.getPrice_ranges().get(i);
                    if (pInfo.isCheck()) {
                        price_ranges_id = "" + pInfo.getId();
                    }
                }
            }

            if (mInfos.getSorts() != null) {
                for (int i = 0; i < mInfos.getSorts().size(); i++) {
                    SortInfo sInfo = mInfos.getSorts().get(i);
                    if (sInfo.isCheck()) {
                        sort_ids = "" + sInfo.getId();
                    }
                }
            }

            if (mInfos.getColor() != null) {
                for (int i = 0; i < mInfos.getColor().size(); i++) {
                    SortInfo coInfo = mInfos.getColor().get(i);
                    if (coInfo.isCheck()) {
                        color = "" + coInfo.getName();
                    }
                }
            }

            nOffset = 0;
            post.setOffset(nOffset);
            post.setId(brandId);
            post.setLimit(40);
            post.setBrand_ids("");
            post.setCount(0);
            post.setCategory_ids(category_ids);
            post.setGenders(genders);
            post.setPrice_ranges_id(price_ranges_id);
            post.setSort_id(sort_ids);
            post.setSize(size);
            post.setColor(color);
            isBottom = false;
            showPreDialog("正在加载中");

            HashMap<String, String> maps = new HashMap<>();
            maps.put("id", String.valueOf(post.getId()));
            maps.put("limit", String.valueOf(post.getLimit()));
            maps.put("offset", String.valueOf(post.getOffset()));
            maps.put("brand_ids", post.getBrand_ids());
            maps.put("genders", post.getGenders());
            maps.put("category_ids", post.getCategory_ids());
            maps.put("sort_id", post.getSort_id());
            maps.put("count", String.valueOf((post.getCount())));
            maps.put("price_ranges_id", post.getPrice_ranges_id());
            maps.put("size", post.getSize());
            maps.put("color", post.getColor());

            new RetrofitRequest<ShopGoodsBrandGoodsObject>(ApiRequest.getApiShiji().getShopGoodsBrandGoods(maps))
                    .handRequest(new MsgCallBack() {
                        @Override
                        public void onResult(HttpMessage msg) {
                            hidePreDialog();
                            if (msg.isSuccess()) {
                                ShopGoodsBrandGoodsObject item = (ShopGoodsBrandGoodsObject) msg.obj;
                                if (item != null && item.getList() != null && item.getList().size() > 0) {
                                    if (mLists != null) {
                                        mLists.clear();
                                    }
                                    mLists.addAll(item.getList());

                                    if (mallGoodsAdapter == null) {
                                        mallGoodsAdapter = new MallGoodsAdapter(getActivity(), mLists, false);
                                        mRecyclerView.setAdapter(mallGoodsAdapter);
                                        mallGoodsAdapter.setOnItemClickListener(new MallGoodsAdapter.OnItemClickListener() {
                                            @Override
                                            public void OnItemClick(final NewGoodsItem info) {
                                                gotoGoodsDetail(info);
                                            }
                                        });
                                    } else {
                                        mRecyclerView.getAdapter().notifyDataSetChanged();
                                        mRecyclerView.scrollToPosition(0);
                                    }
                                    tvDefaultNull.setVisibility(View.GONE);
                                } else {
                                    if (mLists != null) {
                                        mLists.clear();
                                    }
                                    tvDefaultNull.setVisibility(View.VISIBLE);
                                    if (mallGoodsAdapter != null)
                                        mRecyclerView.getAdapter().notifyDataSetChanged();
                                }
                            } else {
                                showToast("请求失败");
                            }
                        }
                    });
        }
    }

    // 加载更多
    private void getOptionPostMoreData() {
        nOffset += 40;
        post.setOffset(nOffset);
        post.setCount(0);

        HashMap<String, String> maps = new HashMap<>();
        maps.put("id", String.valueOf(post.getId()));
        maps.put("limit", String.valueOf(post.getLimit()));
        maps.put("offset", String.valueOf(post.getOffset()));
        maps.put("brand_ids", post.getBrand_ids());
        maps.put("genders", post.getGenders());
        maps.put("category_ids", post.getCategory_ids());
        maps.put("sort_id", post.getSort_id());
        maps.put("count", String.valueOf((post.getCount())));
        maps.put("price_ranges_id", post.getPrice_ranges_id());
        maps.put("size", post.getSize());
        maps.put("color", post.getColor());

        new RetrofitRequest<ShopGoodsBrandGoodsObject>(ApiRequest.getApiShiji().getShopGoodsBrandGoods(maps))
                .handRequest(new MsgCallBack() {
            @Override
            public void onResult(HttpMessage msg) {
                if (msg.isSuccess()) {
                    ShopGoodsBrandGoodsObject item = (ShopGoodsBrandGoodsObject) msg.obj;
                    if (item.getList() != null && item.getList().size() > 0) {
                        isBottom = false;
                        mLists.addAll(item.getList());
                        mRecyclerView.getAdapter().notifyDataSetChanged();
                    } else {
                        isBottom = true;
                    }
                }
            }
        });
    }

    private void gotoGoodsDetail(final NewGoodsItem info){
        if(isEffectClick()) {
            GoodsIdInfo goodsIdInfo = new GoodsIdInfo();
            goodsIdInfo.setGoodsId(info.getId());
            Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
            intent.putExtra("data", new Gson().toJson(goodsIdInfo));
            startActivity(intent);
//            if (isLogin) {
//                GoodsIdInfo goodsIdInfo = new GoodsIdInfo();
//                goodsIdInfo.setGoodsId(info.getId());
//                Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
//                intent.putExtra("data", new Gson().toJson(goodsIdInfo));
//                startActivity(intent);
//            } else {
//                Intent intent = new Intent(getActivity(), LoginActivity.class);
//                startActivityForResult(intent, REQUEST_LOGIN);
//                getActivity().overridePendingTransition(R.anim.slide_in_top_buttom, R.anim.slide_out_top_buttom);
//            }
        }
    }


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.tv_order:
                showOrderPopwindow();
                break;
            case R.id.tv_filter:
                Intent intentGoFilter = new Intent(getActivity(), GoodsListFilterActivity.class);
                intentGoFilter.putExtra("data", new Gson().toJson(mInfos, MallLimitOptionInfo.class));
                intentGoFilter.putExtra("source", SOURCE_BRAND);
                startActivityForResult(intentGoFilter, REQUEST_FILTER);
                getActivity().overridePendingTransition(R.anim.slide_in_bottom_top, R.anim.slide_in_out_fixed);
                break;
        }

//        SortInfo cInfo = new SortInfo();
//        SortInfo delete = null;
//        int nIndex = 0;
//        if (mInfos.getCategories().size() > 2) {
//            delete = mInfos.getCategories().get(2);
//            nIndex = 2;
//        } else {
//            nIndex = mInfos.getCategories().size() - 1;
//            delete = mInfos.getCategories().get(nIndex);
//        }
//        cInfo.setCheck(delete.isCheck());
//        cInfo.setName("所有品类");
//        mInfos.getCategories().remove(nIndex);
//        mInfos.getCategories().add(0, cInfo);

//        activity.OpenRightMenu(mInfos);
    }

    // 弹出左侧排序
    private void showOrderPopwindow() {
        tvOrder.setSelected(true);
        llytOrder = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.fragment_goods_list_order, null);
        rycvOrder = (RecyclerView) llytOrder.findViewById(R.id.rycv_goods_list_order);
        rycvOrder.setItemAnimator(new DefaultItemAnimator());
        rycvOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        goodsListOrderAdapter = new GoodsListOrderAdapter(getActivity(), mInfos);
        rycvOrder.setAdapter(goodsListOrderAdapter);

        int width = SimpleUtils.getScreenWidth(getActivity())/2;
        int heigh = SimpleUtils.getScreenHeight(getActivity()) - SimpleUtils.dp2px(getActivity(), 100);
        orderPopupWindow = new PopupWindow(llytOrder, width, heigh);
        orderPopupWindow.setFocusable(true);
        orderPopupWindow.setOutsideTouchable(true);
        orderPopupWindow.setBackgroundDrawable(new BitmapDrawable(null, ""));
        orderPopupWindow.setAnimationStyle(R.style.order_popwindow_anim_style);

        orderPopupWindow.showAsDropDown(mView.findViewById(R.id.llyt_order_filter), 0, 2);

        goodsListOrderAdapter.setOnItemClickListener(new GoodsListOrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(MallLimitOptionInfo mInfos) {
                getOptionPostData(mInfos);
                orderPopupWindow.dismiss();
            }
        });

        orderPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tvOrder.setSelected(false);
            }
        });

    }

    @Override
    protected void initViews() {

        tvOrder = (TextView) mView.findViewById(R.id.tv_order);
        tvFilter = (TextView) mView.findViewById(R.id.tv_filter);

        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_mall_list);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        rlytNollGoods = (RelativeLayout) mView.findViewById(R.id.rl_reminder);
        tvDefaultNull = (TextView) mView.findViewById(R.id.tv_default_null);
    }

    @Override
    protected void initEvents() {

        tvOrder.setOnClickListener(this);
        tvFilter.setOnClickListener(this);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                // 通过适配器的个数和最后可见的数据来判断是否需要加载数据，这里减3表示后台预加载
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                if ((visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE &&
                        (lastVisibleItemPosition) >= totalItemCount - 19) && !isBottom) {
                    getOptionPostMoreData();
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                StaggeredGridLayoutManager staggeredGridLayoutManager
                        = (StaggeredGridLayoutManager) layoutManager;
                int[] lastPositions = new int[2];
                if (lastPositions == null) {
                    lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];
                }
                staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                lastVisibleItemPosition = Math.max(lastPositions[0], lastPositions[1]);
            }
        });

    }

    @Override
    protected void init() {
        getCategoryData();
        getOptionPostData(mInfos);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == REQUEST_FILTER) {
                String infoData = data.getStringExtra("infoData");
                getOptionPostData(new Gson().fromJson(infoData, MallLimitOptionInfo.class));
            }else if(requestCode == REQUEST_LOGIN){
//                initCarCount();
                isLogin = true;
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if(isVisibleToUser){
            if(((SingleBrandOrderActivity)getActivity()).needOrder){
                initOrderData(((SingleBrandOrderActivity)getActivity()).orderId);
                getOptionPostData(mInfos);
                ((SingleBrandOrderActivity)getActivity()).needOrder = false;
            }
        }
    }

    private void initOrderData(int orderId) {
        for (int i = 0; i < mInfos.getSorts().size(); i++){
            if(i == orderId){
                mInfos.getSorts().get(i).setCheck(true);
            }else {
                mInfos.getSorts().get(i).setCheck(false);
            }
        }
    }
}
